package service

import (
	"errors"
	"fmt"
	"imooc.com/hello/model"
	"imooc.com/hello/util"
	"math/rand"
	"time"
)

type UserService struct {

}
//注册
func (s *UserService) Register (mobile, plainpwd, nickname,
	avatar, sex string) (model.User, error) {
	var user model.User
	//检测手机好是否存在
	_, err := DbEngin.Where("mobile = ?", mobile).Cols("id").Get(&user)
	if  err != nil {
		return user, err
	}

	if user.Id > 0 {
		return user, errors.New("该手机号已注册")
	}

	user.Mobile = mobile
	user.Avatar = avatar
	user.Sex = sex
	user.Nickname = nickname
	user.Salt = fmt.Sprintf("%06d", rand.Int31n(10000))
	user.Passwd = util.MakePasswd(plainpwd, user.Salt)
	user.CreatedAt = time.Now()
	str := fmt.Sprintf("%d", time.Now().Unix())
	user.Token = util.Md5Encode(str)

	_, err = DbEngin.InsertOne(&user)

	return user, err
}

//登录
func (s *UserService) Login(mobile, plainpwd string) (
	model.User, error) {

	var user model.User
	//检测手机好是否存在
	_, err := DbEngin.Where("mobile = ?", mobile).Get(&user)
	if  err != nil {
		return user, err
	}

	if  user.Id <= 0 {
		return user, errors.New("该手机号不存在")
	}

	passwd := util.MakePasswd(plainpwd, user.Salt)

	if user.Passwd != passwd {
		return  user, errors.New("账号或密码错误")
	}

	/**
	 刷新token
	 */
	str := fmt.Sprintf("%d", time.Now().Unix())
	user.Token = util.Md5Encode(str)
	//更新token
	_, err = DbEngin.ID(user.Id).Cols("token").Update(&user)

	return user, err
}

//通过手机号获取user的id
func (s *UserService) LoadByMobile(mobile string)(int64, error){
	var user model.User
	_, err := DbEngin.Where("mobile = ?", mobile).Cols("id").Get(&user)

	if err != nil {
		return 0, err
	}

	return user.Id, nil
}

func (s *UserService) CheckToken(userId int64, token string) bool  {
	var user model.User

	DbEngin.Id(userId).Get(&user)

	return user.Token == token
}
/**
 通过id获取user
 */
func (s *UserService) LoadById(id int64)(model.User, error){
	var user model.User
	_, err := DbEngin.Id(id).Get(&user)

	return user, err
}

